import { DressUpPage } from "../../uiScript/dressUp/DressUpPage";
import { MCommonTipPage } from "../common/MCommonTipPage";
import { GameContextEventMgr } from "../GameContextEventMgr";
import { GameEventCenter } from "../GameEventCenter";
import { DressUpGuideStep } from "../guide/DressUpGuideStep";
import { GuideEvent, GuideMgr } from "../guide/GuideMgr";
import { FuncItemInfo, GlobalObj, LableCfg } from "../obj/GlobalObj";
import { ListDataFactory } from "../obj/ListDataFactory";
import { PGCServer } from "../PGCServer";
import { MTransaction } from "../roleCenter/transaction/MTransaction";
import { SceneMgr } from "../SceneMgr";
import { TaskCenter } from "../task/TaskCenter";
import { GameTool } from "../tool/GameTool";
import { GoodsType, LevelData, ListDataMgr } from "../uiComp/LevelListComp";
import { DressUpData, DressUpFilter } from "./data/DressUpData";
import { DressUpNoteMgr } from "./data/DressUpNoteMgr";
import { DressUpServerDataMgr, DressUpServerTag } from "./data/DressUpServerDataMgr";
import { DressUpDataParse } from "./DressUpDataParse";
import { FaceOperation, FacePartDefine, FacialOrgan, MDressUpAvatarMgr } from "./MDressUpAvatarMgr";
import { MGoodsDescPage } from "./MGoodsDescPage";
import { MGoodsTipPage } from "./MGoodsTipPage";
import { MLotteryClothePage } from "./MLotteryClothePage";
import { MWorkSavePage } from "./MWorkSavePage";

/**
 * 装扮
 */
export class MDressUp {




    private static _ins: MDressUp;
    public static get Ins() {
        return this._ins ||= new MDressUp();
    }

    /**需要过滤掉的list数据 */
    filter: DressUpFilter;
    levelType: string[];
    view: DressUpPage;
    currentDressData: any;

    closeing: boolean;
    clotheHandler: Laya.Handler;

    private _listDataMgr:ListDataMgr<FuncItemInfo>;

    private noteDressMgr: DressUpNoteMgr;
    private guideStep: DressUpGuideStep
    /**
     * 打开装扮界面
     * @param type 默认选中的选项 GoodsType 中的标签
     * @param filter 需要过滤掉的list数据
     * @param levelType 需要的类型 
     */
    open(type?: string, filter?: DressUpFilter, levelType?: string[], guideStep?: any, cb?: Function) {
        if (this.closeing) {
            GameTool.tips("保存角色装扮中...");
            return;
        }
        let avatarMgrIns = MDressUpAvatarMgr.Ins;
        if (!this.noteDressMgr) {
            this.noteDressMgr = new DressUpNoteMgr();
        }
        avatarMgrIns.noteMgr = this.noteDressMgr;

        this.clotheHandler = Laya.Handler.create(avatarMgrIns, avatarMgrIns.changeClothe, null, false);
        this.filter = filter;
        this.levelType = levelType;
        this.guideStep = guideStep;
        this.closeing = false;
        if (MDressUpAvatarMgr.Ins.mClotheMgr.updateGlobalRoleArr)
            MDressUpAvatarMgr.Ins.mClotheMgr.updateGlobalRoleArr(GlobalObj.useData);
        avatarMgrIns.mClotheMgr.isStore = true;
        SceneMgr.open(SceneMgr.DressUpPage, false, [this, type], cb);
    }

    public initListDataMgr(listDataMgr: ListDataMgr<FuncItemInfo>) {
        ListDataFactory.switchDressUp(listDataMgr, GlobalObj.dressState, this.levelType);
        this._listDataMgr = listDataMgr;
    }

    public findLevelData(type:GoodsType): LevelData<FuncItemInfo>{
        if(this._listDataMgr){
            return this._listDataMgr.findData(type as string);
        }
        console.error("还没初始化listDataMgr----");
    }

    init(view: DressUpPage) {
        this.view = view;
    }

    onClick(levelData: LevelData<FuncItemInfo>) {
        if (levelData.type != GoodsType.ZUO_PIN) {
            GlobalObj.isSaveTemp = false; // 重置保存模板标志
        }
    }

    /** 出售 */
    onSell(data: DressUpData, callback?: Laya.Handler) {
        MTransaction.ins.close();

        if (data) {

            console.log("卖出物品")
            if (GlobalObj.getGoodsNum(data) > 1) {
                let recall_price = data.goods_info.recall_price;
                if (recall_price !== data.preform_price * 0.1) {
                    console.warn("配置的出售价格不对---" + data.preform_name + " id:" + data.preform_id);
                }
                MGoodsTipPage.Ins.open([
                    { top: 142, labelCfgs: new LableCfg(data.preform_name, 28) },
                    {
                        top: 192, labelCfgs:
                            new LableCfg("将以" + (recall_price || data.preform_price * 0.1) + "的水晶值拍出", 28, "#000000", 380, true)
                        // new LableCfg((data.preform_price * 0.1) + "", 28, "#C8102E"),
                        // new LableCfg("水晶", 28)

                    },
                ], null, Laya.Handler.create(this, this._onClickSell, [data, callback]), DressUpDataParse.getPlatformImgUrl(data), null);

            } else {
                GameTool.tips("物品数量不足，不能交易");
            }
        } else {
            GameTool.tips("请选择出售的物品");
        }
    }

    private _onClickSell(data: DressUpData, callback: Laya.Handler, isSell: boolean): void {
        debugger;
        if (isSell) {
            //TODO zxy 卖钱
            if (data.goods_info && data.goods_info.goods_id) {
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["deal", { sell: data.preform_name }]);
                PGCServer.ins.sellGoods(data.goods_info.goods_id, Laya.Handler.create(this, (req: any) => {
                    if (req && !req.ret) {
                        callback && callback.run();
                        GameEventCenter.Ins.event(GameEventCenter.UPDATE_CRYSTAL);
                    }
                }), Laya.Handler.create(this, () => {
                    GameTool.tips("卖出失败!!")
                }));
            } else {
                console.warn("卖出数据有问题", data);
            }
        }
    }


    setSelectListType(type: string) {
        this.view && this.view.setSelectListType(type);

    }

    /** 交换 */
    onChange(data: DressUpData, callback?: Laya.Handler) {

        let selectItem = data;
        if (!selectItem) {
            GameTool.tips("请选择需要交换的物品");
            return;
        }

        MTransaction.ins.startTrans(MTransaction.ins.uid, [selectItem]);
    }

    /** 装扮 */
    onDress() {
        MTransaction.ins.close();

    }

    openGoodsDesc(dressUpData: DressUpData) {
        MGoodsDescPage.Ins.open(null, dressUpData
            , Laya.Handler.create(this, this.onClickGoodsDesc, null, false));
    }

    onClickGoodsDesc(isOpen: boolean, goodsData: DressUpData) {
        //TODO 跳转详情页
        if (isOpen) {
            if (goodsData.preform_attribute_desc) {
                let desc = JSON.parse("{" + goodsData.preform_attribute_desc + "}");
                if (desc && desc.purl) {
                    let envVersion = Laya.Browser.window.isReleaseVersion ? 'release' : "trial";
                    let jumpId = Laya.Browser.window.isReleaseApp ? desc.wzid : desc.wtid;
                    GameTool.jumpToMini(jumpId, desc.path, envVersion);
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["ecmp", { page_url: desc.path, product_name: goodsData.preform_name, product_code: goodsData.preform_id }]);
                }
            }
            console.log("跳转详情")
        }
    }

    onSaveTemplete(data: DressUpData, callback?: Laya.Handler) {
        this.currentDressData = data;
        GlobalObj.isSaveTemp = true;
        this.setSelectListType(GoodsType.ZUO_PIN);
    }

    onReplaceTemplete(data: DressUpData, callback?: Laya.Handler) {
        if (data) {
            // "确认替换模板" + data.preform_name + "吗?"
            MCommonTipPage.open("替换旧妆扮，来点新鲜感吗？", null, Laya.Handler.create(this, () => {
                console.log("替换模板", data);
                let iconImg = this._createTempIconImg()[0];
                this._upadteTemplete(data.preform_id, data.preform_name, iconImg, "替换作品模板成功！", callback, data);
                // callback && callback.runWith(data);
            }));
        } else {

            GameTool.tips("请选择需要替换的模板");
        }
    }

    onNewTemplete(callback?: Laya.Handler) {
        let iconImg = this._createTempIconImg(true);
        if (iconImg[0]) {
            // iconImg.scale(2,2);
            MWorkSavePage.Ins.open(iconImg[1], Laya.Handler.create(this, (tempName: string) => {
                this._upadteTemplete(null, tempName, iconImg[0], "上传作品模板成功！", callback);
            }));
        }
    }

    private tempJson: string;
    private tempUrl: string;

    /** 上传作品模板 */
    private _upadteTemplete(id: number, name: string, img: Laya.Image, tips: string, callback: Laya.Handler, originData?: any) {
        this.tempJson = null;
        this.tempUrl = null;
        GameTool.tips("保存模板中...", false, 0, 2000);
        var sucHandler = Laya.Handler.create(this, (json: string, url: string, data: any) => {
            if (data && !data.ret) {
                GameTool.tips(tips);
                if (originData) {
                    originData.developer_avatar_img = url;
                    originData.developer_avatar_json = json;
                }
                callback && callback.run();
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["save _template", { works_name: name }]);
                if (this.currentDressData) {
                    let _type = DressUpServerDataMgr.Ins.gettagMap(this.currentDressData);
                    if (this.currentDressData.preform_type == DressUpServerTag.WU_GUAN_TAG) {
                        this.dataReport2(GoodsType.WU_GUAN, _type);
                    }
                    else if (this.currentDressData.preform_type == DressUpServerTag.ZHUANG_RONG_TAG) {
                        this.dataReport2(GoodsType.ZHUANG_RONG, _type);
                    }
                    else if (this.currentDressData.preform_type == 68) {
                        let _type2 = DressUpServerDataMgr.Ins.gettagMap(this.currentDressData, 0);
                        this.dataReport2(GoodsType.FU_SHI, _type2);
                    }
                }
            }
        }, []);
        MDressUpAvatarMgr.Ins.getAvatarJson(Laya.Handler.create(this, (json: any) => {
            this.tempJson = JSON.stringify(json);
            if (this.tempJson && this.tempUrl) {
                sucHandler.args.push(this.tempJson, this.tempUrl);
                PGCServer.ins.updateDeveloperAvatar(id, name, this.tempUrl, this.tempJson, sucHandler);
            }
        }));

        this.uploadImgToTempIcon(img, Laya.Handler.create(this, (url: string) => {
            this.tempUrl = url;
            if (this.tempJson && this.tempUrl) {
                sucHandler.args.push(this.tempJson, this.tempUrl);
                PGCServer.ins.updateDeveloperAvatar(id, name, this.tempUrl, this.tempJson, sucHandler);
            }
        }));
    }

    initFirstDressConfig() {
        var item = Laya.LocalStorage.getItem("FIRST_CLICK_DRESS");
        if (!item) {
            var obj: any = {};
            obj.features_eyes = 0;
            obj.features_lip = 0;
            obj.features_hair = 0;
            obj.features_eyelash = 0;
            obj.makeup_liquidfoundation = 0;
            obj.makeup_settingpowder = 0;
            obj.makeup_blush = 0;
            obj.makeup_contour = 0;
            obj.makeup_lipstick = 0;
            obj.makeup_eyeshadow = 0;
            obj.makeup_eyeliner = 0;
            obj.makeup_mascara = 0;
            obj.makeup_eyebrowpencil = 0;
            obj.clothing_top = 0;
            obj.clothing_bottom = 0;
            obj.clothing_socks = 0;
            obj.clothing_shoes = 0;
            obj.clothing_accessory = 0;
            Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(obj));
        }
    }

    getFirstDressConfig() {
        var item1 = Laya.LocalStorage.getItem("FIRST_CLICK_DRESS");
        var _data = JSON.parse(item1);
        return _data;
    }

    dataReport2(pretype: GoodsType, type: GoodsType) {
        this.initFirstDressConfig();
        var _data = this.getFirstDressConfig();
        if (pretype == GoodsType.WU_GUAN) {
            switch (type) {
                case GoodsType.W_YAN_JING:
                    if (_data.features_eyes == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_features", { features_eyes: "眼睛" }]);
                        _data.features_eyes = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_features", { features_eyes: "眼睛" }]);
                    }
                    break;
                case GoodsType.W_ZUI_CHUN:
                    if (_data.features_lip == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_features", { features_lip: "唇形" }]);
                        _data.features_lip = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_features", { features_lip: "唇形" }]);
                    }
                    break;
                case GoodsType.W_TOU_FA:
                    if (_data.features_hair == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_features", { features_hair: "头发" }]);
                        _data.features_hair = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_features", { features_hair: "头发" }]);
                    }
                    break;
                case GoodsType.W_JIE_MAO:
                    if (_data.features_eyelash == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_features", { features_eyelash: "睫毛" }]);
                        _data.features_eyelash = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_features", { features_eyelash: "睫毛" }]);
                    }
                    break;
                default:
                    break;
            }
        }
        else if (pretype == GoodsType.ZHUANG_RONG) {
            switch (type) {
                case GoodsType.Z_FEN_DI_YE:
                    if (_data.makeup_liquidfoundation == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_liquidfoundation: "粉底液" }]);
                        _data.makeup_liquidfoundation = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_liquidfoundation: "粉底液" }]);
                    }
                    break;
                case GoodsType.Z_DING_ZHUANG:
                    if (_data.makeup_settingpowder == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_settingpowder: "大白饼" }]);
                        _data.makeup_settingpowder = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_settingpowder: "大白饼" }]);
                    }
                    break;
                case GoodsType.Z_SAI_HONG:
                    if (_data.makeup_blush == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_blush: "腮红" }]);
                        _data.makeup_blush = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_blush: "腮红" }]);
                    }
                    break;
                case GoodsType.Z_XIU_RONG:
                    if (_data.makeup_contour == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_contour: "修容" }]);
                        _data.makeup_contour = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_contour: "修容" }]);
                    }
                    break;
                case GoodsType.Z_KOU_HONG:
                    if (_data.makeup_lipstick == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_lipstick: "口红" }]);
                        _data.makeup_lipstick = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_lipstick: "口红" }]);
                    }
                    break;
                case GoodsType.Z_YAN_YING:
                    if (_data.makeup_eyeshadow == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_eyeshadow: "眼影" }]);
                        _data.makeup_eyeshadow = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_eyeshadow: "眼影" }]);
                    }
                    break;
                case GoodsType.Z_YAN_XIAN:
                    if (_data.makeup_eyeliner == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_eyeliner: "眼线" }]);
                        _data.makeup_eyeliner = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_eyeliner: "眼线" }]);
                    }
                    break;
                case GoodsType.W_JIE_MAO:
                    if (_data.makeup_mascara == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_mascara: "睫毛膏" }]);
                        _data.makeup_mascara = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_mascara: "睫毛膏" }]);
                    }
                    break;
                case GoodsType.Z_MEI_MAO:

                    if (_data.makeup_eyebrowpencil == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_makeup", { makeup_eyebrowpencil: "眉笔" }]);
                        _data.makeup_eyebrowpencil = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_makeup", { makeup_eyebrowpencil: "眉笔" }]);
                    }
                    break;
                default:
                    break;
            }
        }
        else if (pretype == GoodsType.FU_SHI) {
            switch (type) {
                case GoodsType.UPPER:
                    if (_data.clothing_top == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_clothing", { clothing_top: "上衣" }]);
                        _data.clothing_top = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_clothing", { clothing_top: "上衣" }]);
                    }
                    break;
                case GoodsType.LOWER:
                    if (_data.clothing_bottom == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_clothing", { clothing_bottom: "下衣" }]);
                        _data.clothing_bottom = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_clothing", { clothing_bottom: "下衣" }]);
                    }
                    break;
                case GoodsType.WA_ZI:
                    if (_data.clothing_socks == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_clothing", { clothing_socks: "袜子" }]);
                        _data.clothing_socks = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_clothing", { clothing_socks: "袜子" }]);
                    }
                    break;
                case GoodsType.SHOE:
                    if (_data.clothing_shoes == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_clothing", { clothing_shoes: "鞋子" }]);
                        _data.clothing_shoes = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_clothing", { clothing_shoes: "鞋子" }]);
                    }
                    break;
                case GoodsType.W_HAT:
                    if (_data.clothing_accessory == 0) {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["first_choose_clothing", { clothing_accessory: "配饰" }]);
                        _data.clothing_accessory = 1;
                        Laya.LocalStorage.setItem("FIRST_CLICK_DRESS", JSON.stringify(_data));
                    }
                    else {
                        GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_choose_clothing", { clothing_accessory: "配饰" }]);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private _createTempIconImg(isDouble?: boolean): any {
        if (!this.view) {
            return;
        }
        let renderImg = GameTool.seekChildByName("rImage", this.view.roleBox) as Laya.Image;
        if (!renderImg) {
            return GameTool.tips("角色还没初始化完成");
        }
        let width: number = 467, height: number = 625;
        let offsetY = 0; // 修改切图位置
        let txture: Laya.HTMLCanvas = renderImg.drawToCanvas(width, height, 0, offsetY);
        let base64 = txture.toBase64("image/png", 1);

        let img = new Laya.Image();
        img.on(Laya.Event.LOADED, this, () => {
            //@ts-ignore
            img["isloadroleIcon"] = true;
            img.event("loadRoleIconOver");
        });
        img.skin = base64;
        GameTool.adaptiveImage(img, width, height, 110);
        let result = [img];
        if (isDouble) {
            let img2 = new Laya.Image();
            img2.on(Laya.Event.LOADED, this, () => {
                //@ts-ignore
                img2["isloadroleIcon"] = true;
                img2.event("loadRoleIconOver");
            });
            img2.skin = base64;
            GameTool.adaptiveImage(img2, width, height, 212);
            result.push(img2);
        }
        // 测试代码
        // Laya.stage.addChild(img);
        // img.centerX = img.centerY = 0;
        return result;
    }

    private uploadImgToTempIcon(img: Laya.Sprite, callback: Laya.Handler) {
        if (!img || img.destroyed) {
            callback && callback.runWith("");
            return console.error("图片已被销毁");
        }

        //@ts-ignore
        if (!img["isloadroleIcon"]) {
            img.once("loadRoleIconOver", this, this.uploadImgToTempIcon, [img, callback]);
            return;
        }
        Laya.timer.frameOnce(1, this, () => {
            img.removeSelf();
            GameContextEventMgr.sendGlobalEvent("pgc_getImageArrayBuffer", [img, Laya.Handler.create(this, (buffer: any, type: string) => {
                img.destroy();
                PGCServer.ins.uploadPictureToServer(buffer, type, Laya.Handler.create(this, (dataO: any) => {
                    if (dataO.success && dataO.data) {
                        let url = dataO.data.filepath;
                        if (url && url.length) {
                            callback && callback.runWith(url); // 这个url需要转换
                        }
                    }
                }));
            })])
        })
    }

    onClickBuy(data: DressUpData, callback?: Laya.Handler) {

        let selectItem = data;
        if (selectItem) {
            //TODO 购买
            MCommonTipPage.openSp([
                {
                    top: 90,
                    labelCfgs: new LableCfg("是否使用" + data.preform_price + "的水晶值购买", 24, "#000000", 380, true)
                },
                {
                    top: 130,
                    labelCfgs: new LableCfg(data.preform_name + "（产品 ）", 24, "#000000", 380, true)
                }
            ], null, Laya.Handler.create(this, this.onConfirmBuy, [selectItem, callback]));
            // MCommonTipPage.open("是否使用"+data.preform_price+"的水晶值购买"+data.preform_name+"（产品 ）", null, Laya.Handler.create(this, this.onConfirmShop, [selectItem,callback]));
        } else {
            GameTool.tips("请选择购买的物品");
        }
    }

    buyDressReport(type: GoodsType, _name: string) {
        switch (type) {
            case GoodsType.Z_FEN_DI_YE:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_liquidfoundation: _name }]);
                break;
            case GoodsType.Z_DING_ZHUANG:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_settingpowder: _name }]);
                break;
            case GoodsType.Z_SAI_HONG:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_blush: _name }]);
                break;
            case GoodsType.Z_XIU_RONG:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_contour: _name }]);
                break;
            case GoodsType.Z_KOU_HONG:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_lipstick: _name }]);
                break;
            case GoodsType.Z_YAN_YING:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_eyeshadow: _name }]);
                break;
            case GoodsType.Z_YAN_XIAN:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_eyeliner: _name }]);
                break;
            case GoodsType.W_JIE_MAO:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_mascara: _name }]);
                break;
            case GoodsType.Z_MEI_MAO:
                GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_buy", { makeup_eyebrowpencil: _name }]);
                break;
            default:
                break;
        }
    }

    private onConfirmBuy(data: DressUpData, callback: Laya.Handler): void {
        let _data = data;
        let _type = DressUpServerDataMgr.Ins.gettagMap(_data);
        PGCServer.ins.buyGoods(data.preform_id, Laya.Handler.create(this, (data: any) => {
            // 购买打点统一放到 setOwnDress一起处理
            if (data && !data.ret) {
                callback && callback.run();
                this.noteDressMgr.setOwnDress(_data.preform_id);
                GuideMgr.ins.eventCenter.event(GuideEvent.buyGoods);
            }
            GameEventCenter.Ins.event(GameEventCenter.UPDATE_CRYSTAL);
        }))
    }

    /** 点击列表，
     * @param data 有效物品
     */
    onClickListItem(data: DressUpData, curdressUpData: DressUpData, levelData: LevelData<FuncItemInfo>): void {
        GameEventCenter.Ins.event(GameEventCenter.SELECT_ITEM, [data, curdressUpData, levelData]);
    }

    dataReport(pretype: GoodsType, type: GoodsType, _name: string) {
        if (pretype == GoodsType.WU_GUAN) {
            switch (type) {
                case GoodsType.W_YAN_JING:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { features_eyes: _name }]);
                    break;
                case GoodsType.W_ZUI_CHUN:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { features_lip: _name }]);
                    break;
                case GoodsType.W_TOU_FA:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { features_hair: _name }]);
                    break;
                case GoodsType.W_JIE_MAO:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { features_eyelash: _name }]);
                    break;
                default:
                    break;
            }
        }
        else if (pretype == GoodsType.ZHUANG_RONG) {
            switch (type) {
                case GoodsType.Z_FEN_DI_YE:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_liquidfoundation: _name }]);
                    break;
                case GoodsType.Z_DING_ZHUANG:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_settingpowder: _name }]);
                    break;
                case GoodsType.Z_SAI_HONG:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_blush: _name }]);
                    break;
                case GoodsType.Z_XIU_RONG:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_contour: _name }]);
                    break;
                case GoodsType.Z_KOU_HONG:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_lipstick: _name }]);
                    break;
                case GoodsType.Z_YAN_YING:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_eyeshadow: _name }]);
                    break;
                case GoodsType.Z_YAN_XIAN:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_eyeliner: _name }]);
                    break;
                case GoodsType.W_JIE_MAO:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_mascara: _name }]);
                    break;
                case GoodsType.Z_MEI_MAO:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { makeup_eyebrowpencil: _name }]);
                    break;
                default:
                    break;
            }
        }
        else if (pretype == GoodsType.FU_SHI) {
            switch (type) {
                case GoodsType.UPPER:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { clothing_top: _name }]);
                    break;
                case GoodsType.LOWER:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { clothing_bottom: _name }]);
                    break;
                case GoodsType.WA_ZI:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { clothing_socks: _name }]);
                    break;
                case GoodsType.SHOE:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { clothing_shoes: _name }]);
                    break;
                case GoodsType.W_HAT:
                    GameContextEventMgr.sendGlobalEvent("narsReportData", ["dressup_view", { clothing_accessory: _name }]);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 清除对应妆容的数据
     * @param _selectDatas 选中妆容数据 
     * @param _selectLevelData 二级菜单
     */
    clearTabDressUp(_selectDatas: Map<string, DressUpData>, _selectLevelData: LevelData<FuncItemInfo>) {
        let type = _selectLevelData.type;
        let pretype = _selectLevelData.preNode.type;
        this.clearTabDressUpToLevelType(type, pretype);
    }

    /**
     * 清理妆容菜单层级对应的 捏脸部位
     * @param type 最低级标签
     * @param pretype 次低级标签
     */
    public clearTabDressUpToLevelType(type: GoodsType, pretype: GoodsType) {
        let dressAaMgr = MDressUpAvatarMgr.Ins;
        if (type == GoodsType.Z_SAI_HONG) {
            dressAaMgr.clearDiffPart(FacialOrgan.Cheek);
        } else if (type == GoodsType.Z_KOU_HONG || pretype == GoodsType.Z_KOU_HONG) {
            dressAaMgr.clearDiffPart(FacialOrgan.Mouse);
            dressAaMgr.changeMaskTex(FacialOrgan.Mouse, null);
        } else if (type == GoodsType.Z_DING_ZHUANG) {
            dressAaMgr.clearDiffPart(FacialOrgan.Fixing);
        } else if ([type, pretype].indexOf(GoodsType.Z_YAN_YING) >= 0) {
            dressAaMgr.clearDiffPart(FacialOrgan.EyeShadow);
        } else if (type == GoodsType.Z_JIE_MAO) {
            dressAaMgr.clearMatProps(FaceOperation.EyelashColor);
        } else if (type == GoodsType.Z_MEI_MAO) {
            dressAaMgr.clearDiffPart(FacialOrgan.EyeBrow);
        } else if (type == GoodsType.Z_YAN_XIAN) {
            dressAaMgr.clearDiffPart(FacialOrgan.EyeLiner);
        } else if (type == GoodsType.Z_FEN_DI_YE || pretype == GoodsType.Z_FEN_DI_YE) {
            dressAaMgr.clearDiffPart(FacialOrgan.Base);
            dressAaMgr.clearMatProps(FaceOperation.SkinSmoothness);
        } else if (type == GoodsType.Z_XIU_RONG) {
            dressAaMgr.clearDiffPart(FacialOrgan.Bronzer);
        }
        let partType = this.noteDressMgr.getPartByLevelType(type, pretype);
        this.noteDressMgr.updateDressUpMap(partType, null);
        let levelData = this.view.listDataMgr.findData(type as string);
        this.noteDressMgr.del(levelData);
    }

    /** 更新妆容 
     * 多色拼盘只能使用画法贴图实现，不能使用颜色+画法双选
    */
    onClickDressUpItem(levelData: LevelData<FuncItemInfo>, map: Map<string, DressUpData>, curSelectData: DressUpData) {
        let type = levelData.type;
        let pretype = levelData.preNode.type;
        let p_pretype = levelData.preNode.preNode && levelData.preNode.preNode.type;
        let items = map.values();
        let colors, tex, valueIter, value: any, ab: any, maskTex;
        MDressUpAvatarMgr.Ins.needSaveAvatar = !!curSelectData || MDressUpAvatarMgr.Ins.needSaveAvatar;
        let isClothe = pretype == GoodsType.WU_GUAN && type == GoodsType.W_HAT;

        if ((type == GoodsType.WU_GUAN || pretype == GoodsType.WU_GUAN) && !isClothe) { // 五官

            valueIter = items.next();
            while (valueIter && valueIter.value) {
                value = valueIter.value;
                if (value.color) {
                    colors = value.color;
                } else {
                    ab = value.preform_info.dataFile;
                    tex = value.preform_info.albedoTexture;
                }
                valueIter = items.next();
                this.dataReport(pretype, type, value.preform_name)
                // MDressUpAvatarMgr.Ins.updateDressUpMap(value.preform_type, value.preform_id);
            }
            // console.log("tex tex tex:",tex);
            tex = DressUpDataParse.getTextureUrl(tex);
            ab && MDressUpAvatarMgr.Ins.setDressUpPrefab(ab);
            if (type == GoodsType.W_JIE_MAO) {
                tex && MDressUpAvatarMgr.Ins.changeMatPropsByTex(FaceOperation.EyelashTexture, tex);
            }
            if (type == GoodsType.W_YAN_JING) {
                MDressUpAvatarMgr.Ins.changeDressUp(colors, tex, FacialOrgan.Eye);
            }
        } else if (pretype == GoodsType.ZHUANG_RONG || p_pretype == GoodsType.ZHUANG_RONG) {

            this.noteDressMgr.add(curSelectData, levelData);

            valueIter = items.next();
            while (valueIter && valueIter.value) {
                value = valueIter.value;
                if (value.color) {
                    colors = value.color;
                }
                if (value.preform_info && value.preform_info.albedoTexture) {
                    if (tex) {
                        console.warn("已经存在贴图了 为啥还有数据:", items);
                    }
                    tex = value.preform_info.albedoTexture;
                }
                if (value.preform_info && value.preform_info.maskTexture) {
                    if (maskTex) {
                        console.warn("已经存在maskTex贴图了 为啥还有数据:", items);
                    }
                    maskTex = value.preform_info.maskTexture;
                }
                valueIter = items.next();
                if (pretype == GoodsType.ZHUANG_RONG) {
                    this.dataReport(pretype, type, value.preform_name);
                }
                else if (p_pretype == GoodsType.ZHUANG_RONG) {
                    this.dataReport(p_pretype, pretype, value.preform_name);
                }
            }

            if (!colors && !tex && !maskTex) return;
            tex = DressUpDataParse.getTextureUrl(tex);
            maskTex = DressUpDataParse.getTextureUrl(maskTex);
            let shapeData = map.get("dressDownList"); // 形状数据
            if(shapeData){
                let partType = this.noteDressMgr.getPartByLevelType(type, pretype);
                this.noteDressMgr.updateDressUpMap(partType, shapeData.preform_id, 1);
            }
            this.editDressUp(type, pretype, colors, tex, maskTex, curSelectData);

        } else if (pretype == GoodsType.TAO_ZHUANG || type == GoodsType.TAO_ZHUANG) { // 抽奖套装
            if (curSelectData)
                // MDressUpAvatarMgr.Ins.mClotheMgr.clickClothe(curSelectData);
                this.dataReport(pretype, type, curSelectData.preform_desc)
        } else if (pretype == GoodsType.FU_SHI || type == GoodsType.FU_SHI || isClothe) { // 服饰
            if (curSelectData) {
                MDressUpAvatarMgr.Ins.mClotheMgr.clickClothe(curSelectData);
                this.dataReport(pretype, type, curSelectData.preform_name)
            }
        } else if (type == GoodsType.ZUO_PIN) {
            if (curSelectData && curSelectData.developer_avatar_json) {
                if (GlobalObj.isSaveTemp) {
                    // 可替换，这里应该是按钮那边处理了
                } else {
                    MDressUpAvatarMgr.Ins.setAvatarData(JSON.parse(curSelectData.developer_avatar_json));
                }
            }
        }
    }

    /**
     * 修改妆容
     * @param type 最小子分类
     * @param pretype 妆容分类
     * @param colors 颜色数组
     * @param tex 贴图url
     * @param curSelectData 当前选中的数据 
     * @returns void
     */
    editDressUp(type: GoodsType, pretype: GoodsType, colors: string[], tex: string, maskTex: string, curSelectData: DressUpData) {
        if(! curSelectData){
            return console.error("==================没有选中妆容数据================");
        }
        let dressMgr = MDressUpAvatarMgr.Ins;
        let id = curSelectData.preform_id;
        if (type == GoodsType.Z_SAI_HONG) {
            dressMgr.changeDressUp(colors, tex, FacialOrgan.Cheek);
        } else if (type == GoodsType.Z_KOU_HONG || pretype == GoodsType.Z_KOU_HONG) {
            dressMgr.changeDressUp(colors, tex, FacialOrgan.Mouse);
            dressMgr.changeMaskTex(FacialOrgan.Mouse, maskTex);
        } else if (type == GoodsType.Z_DING_ZHUANG) {
            dressMgr.changeDressUp(colors, tex, FacialOrgan.Fixing);
            dressMgr.changeMaskTex(FacialOrgan.Base, maskTex);
        } else if ([type, pretype].indexOf(GoodsType.Z_YAN_YING) >= 0) {
            if (colors && colors.length > 1) {
                // 多色盘
                colors = null;
            }
            dressMgr.changeDressUp(colors, tex, FacialOrgan.EyeShadow);

        } else if (type == GoodsType.Z_JIE_MAO) {
            dressMgr.changeDressUp(colors, tex, FaceOperation.EyelashColor);

        } else if (type == GoodsType.Z_MEI_MAO) {
            tex = PGCServer.ins.formatUrl("upload/svn/resource/nars/chuan/eyebrow_base.png");
            dressMgr.changeDressUp(colors, tex, FacialOrgan.EyeBrow);

        } else if (type == GoodsType.Z_YAN_XIAN) {
            dressMgr.changeDressUp(colors, tex, FacialOrgan.EyeLiner);

        } else if (type == GoodsType.Z_FEN_DI_YE || pretype == GoodsType.Z_FEN_DI_YE) {
            if (!curSelectData) return;
            let faceEdit = dressMgr.faceEdit;
            tex = DressUpDataParse.getTextureUrl(curSelectData.preform_info.albedoTexture);
            let smoothess = 0;
            switch (type) {
                case GoodsType.LIU_GUANG_MEI_JI:
                    smoothess = 0.8;
                    break;
                case GoodsType.ROU_YA:
                    smoothess = 0;

                    break;
                case GoodsType.LIANG_CAI:
                    smoothess = 0.75;

                    break;

                default:
                    break;
            }

            dressMgr.changeDressUp(null, tex, FacialOrgan.Base);
            // faceEdit.changeMatProps(FaceOperation.SkinColor, color && GameTool.getColorObj(color)[0]);
            faceEdit.changeMatProps(FaceOperation.SkinSmoothness, smoothess);
        } else if (type == GoodsType.Z_XIU_RONG) {
            colors = undefined;
            dressMgr.changeDressUp(colors, tex, FacialOrgan.Bronzer);

        }
        let partType = this.noteDressMgr.getPartByLevelType(type, pretype);
        this.noteDressMgr.updateDressUpMap(partType, id, 0);

    }

    /**
     * 还原未拥有的妆容数据
     */
    public recoverNoOwnDress() {
        if (this.noteDressMgr) {
            this.noteDressMgr.noOwnDressUpDatas.forEach(((item: DressUpData, key: string) => {
                // let data = this.noteDressMgr.ownDressUpDatas.get(key);
                // console.log("还原的部位:" + key + "  dressName:" + (data && data.preform_name));
                this.recoverDressUp(key, null);
            }));
        }
    }

    public getSelectIdxArr(levelData: LevelData<FuncItemInfo>):number[]{
        if(this.noteDressMgr){
            return this.noteDressMgr.getSelectIdxArr(levelData);
        }
        return [];
    }

    /**
     * 还原装扮数据, 这里不针对画法
     * @param key note 记录的map的key
     * @param data 老的妆容数据
     */
    public recoverDressUp(key: string, data: DressUpData) {
        let arr = key.split(","); // noteMgr中的父级和子级进行层级设置
        if (data) {
            let colors: string[], tex: string, maskTex;
            if (data.color) {
                colors = data.color;
            }
            if (data.preform_info && data.preform_info.albedoTexture) {
                if (tex) {
                    console.warn("已经存在贴图了 为啥还有数据:", data);
                }
                tex = data.preform_info.albedoTexture;
            }
            if (data.preform_info && data.preform_info.maskTexture) {
                if (maskTex) {
                    console.warn("已经存在maskTex贴图了 为啥还有数据:", data);
                }
                maskTex = data.preform_info.maskTexture;
            }
            tex = DressUpDataParse.getTextureUrl(tex);
            maskTex = DressUpDataParse.getTextureUrl(maskTex);
            // 使用老的记录的妆容数据
            this.editDressUp(arr[0], arr[1], colors, tex, maskTex, data);
        } else {
            // 还原默认
            this.clearTabDressUpToLevelType(arr[0], arr[1]);
        }
    }



    onLottery(data: DressUpData, callback?: Laya.Handler) {
        MLotteryClothePage.Ins.open();
    }
    onClickNextStep(data: DressUpData) {
        // if (data) {
        this.guideStep && this.guideStep.nextStep(data);
        // } else {
        //     GameTool.tips("未选中样式");
        // }


    }

    changeTableDisable(disableTypes: any[],) {
        let mgr = this.view && this.view.listDataMgr;
        if (!mgr) return;
        mgr.map((v) => {
            if (v && v.data) {
                v.data.disable = disableTypes.indexOf(v.type) >= 0;
            }
        });
    }

    close() {

        this.closeing = true;
        console.log("this.closeing:" + this.closeing);
        if (GlobalObj.dressState == 2) {
            this.noteDressMgr.saveNewPlayer();
            this._clear();
        } else {
            this.recoverNoOwnDress();
            this._clear();
            // 购买未购买的流程 ，现在不需要了....
            // this.noteDressMgr.buyNoOwnDress(Laya.Handler.create(this, this._clear))
        }

    }

    private _clear() {
        MDressUpAvatarMgr.Ins.saveDressUpAvatar(Laya.Handler.create(this, ()=>{
            this.closeing = false;
            console.log("this.closeing  save over:" + this.closeing);
        }));
        MDressUpAvatarMgr.Ins.clear();
        this.filter = null;
        this.levelType = null;
        this.view = null;
        this.clotheHandler && this.clotheHandler.recover();
        this.clotheHandler = null;
        MTransaction.ins.close();
        SceneMgr.close(SceneMgr.DressUpPage);
        SceneMgr.close(SceneMgr.GoodsDescPage);
        this.currentDressData = null;
    }
}